<script setup>
import { computed, ref, watch } from 'vue'
import { getOptions } from '@/utils'
import { message } from 'ant-design-vue'
import api from '@/api/index.js'
import SltFromTable from '@/components/SltFromTable/SltFromTable.vue'
import FarmNj from '@/views/FarmDevManage/FarmNj/FarmNj.vue'
import SysUser from '@/views/SystemManage/SysUser/Child/AppUser/AppUser.vue'
import { phoneRule } from '@/utils/checkRule.js'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  },
  faMenuSltOpt: {
    type: Array,
    default: () => []
  }
})

// 弹窗标题
const title = computed(() => (props.curRow.orderId ? '编辑数据' : '新增数据'))
// 表单数据
const formData = ref({
  workType: [],
  machineType: '',
  machineId: '',
  farmingArea: '',
  farmingAddress: '',
  applyUserName: '',
  applyUserPhone: '',
  receiveUserId: '',
  serviceRemark: '',
  numberPlots: 1
})

// 新增动态获取作业类型选项的状态
const workTypeOptions = ref([])

//获取作业类型
const getWorkType = async (newType) => {
  try {
    const workTypes = await api.getMachinWorkType({ machineType: newType })
    workTypeOptions.value = workTypes.data.map((item) => {
      return {
        value: item.workType,
        label: item.workType
      }
    })
  } catch (error) {
    console.log(error)
  }
}

// 监听农机类型的变化，动态更新作业类型选项
watch(
  () => formData.value.machineType,
  async (newType) => {
    if (newType) {
      getWorkType(newType)
      formData.value.workType = []
    } else {
      workTypeOptions.value = []
    }
  }
)

//选着农机时自动匹配农机类型字段
const onMachineSelected = (machine) => {
  if (machine && machine.machineType) {
    formData.value.machineType = machine.machineType
  }
}

// 同步表格数据到表单数据内
watch(
  () => props.curRow,
  async (val) => {
    // 按钮类型的父节点id为数组，需要特殊处理
    formData.value = { ...formData.value, ...val }
    if (val.orderId && show.value) {
      const { data } = await api.getFarInfo({ id: val.orderId })
      formData.value = {
        ...formData.value,
        ...val,
        ...data,
        workType: data.workType ? data.workType.split(',') : []
      }
    } else {
      formData.value = {
        workType: [],
        machineType: '',
        machineId: '',
        farmingArea: '',
        farmingAddress: '',
        applyUserName: '',
        applyUserPhone: '',
        receiveUserId: '',
        serviceRemark: '',
        numberPlots: 1
      }
    }
  },
  { deep: true, immediate: true }
)
// 是否显示弹窗
const show = ref(false)
// 弹窗显示状态切换时触发
const afterOpenChange = (bool) => {
  if (!bool) {
    formData.value = {
      workType: [],
      machineType: '',
      machineId: '',
      farmingArea: '',
      farmingAddress: '',
      applyUserName: '',
      applyUserPhone: '',
      receiveUserId: '',
      serviceRemark: '',
      numberPlots: 1
    }
    emits('close')
  }
}
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      workType: info.workType.join(',')
    }
    if (params.receiveUserId) {
      params.orderStatus = 2
    }
    await api.editFar(params)
    message.success('编辑成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('reload')
  } catch (err) {
  } finally {
    submitLoading.value = false
  }
}
// 新增数据
const addItem = async (info) => {
  console.log(info)
  try {
    submitLoading.value = true
    let params = {
      ...formData.value,
      ...info,
      createdType: 1,
      workType: info.workType.join(',')
    }
    if (params.receiveUserId) {
      params.orderStatus = 2
    }
    await api.addFar(params)
    message.success('新增成功')
    show.value = false
    setTimeout(() => {
      submitLoading.value = false
    }, 30)
    emits('reload')
  } catch (err) {
    message.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 表单提交，验证通过了
const onFinish = (values) => {
  if (formData.value.orderId) {
    emitItem(values)
  } else {
    addItem(values)
  }
}
// 验证失败
const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo)
}
// 打开弹窗
const open = () => {
  show.value = true
}
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value.validateFields().then(onFinish).catch(onFinishFailed)
}
defineExpose({ open })
</script>

<template>
  <a-drawer
    :maskClosable="false"
    :closable="false"
    destroyOnClose
    v-model:open="show"
    class="custom-class"
    root-class-name="root-class-name"
    :title="title"
    placement="right"
    @after-open-change="afterOpenChange"
  >
    <a-form
      ref="formRef"
      :model="formData"
      layout="vertical"
      autocomplete="off"
      @finish="onFinish"
      @finishFailed="onFinishFailed"
    >
      <a-form-item
        v-if="!props.curRow.orderId"
        label="农机"
        name="machineId"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-form-item-rest>
          <SltFromTable
            v-model="formData.machineId"
            :component="FarmNj"
            :fieldNames="{ name: 'machineName', id: 'machineId' }"
            :nameValue="formData.machineName"
            @selected-machine="onMachineSelected"
          />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item
        v-if="!props.curRow.orderId"
        label="农机类型"
        name="machineType"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.machineType"
          :options="getOptions('machine_type')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>
      <a-form-item label="作业类型" v-if="formData.machineType" name="workType">
        <a-select
          v-model:value="formData.workType"
          :options="workTypeOptions"
          allowClear
          mode="multiple"
        >
        </a-select>
      </a-form-item>
      <a-form-item
        v-if="!props.curRow.orderId"
        label="土地类型"
        name="fieldType"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-select
          v-model:value="formData.fieldType"
          :options="getOptions('field_type')"
          allowClear
          :fieldNames="{ label: 'constLabel', value: 'constValue' }"
        />
      </a-form-item>

      <a-form-item
        v-if="!props.curRow.orderId"
        label="耕作面积(亩)"
        name="farmingArea"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number :min="1" v-model:value="formData.farmingArea" allowClear />
      </a-form-item>
      <a-form-item
        v-if="!props.curRow.orderId"
        label="耕作地块数"
        name="numberPlots"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input-number :min="1" v-model:value="formData.numberPlots" allowClear />
      </a-form-item>
      <a-form-item
        v-if="!props.curRow.orderId"
        label="耕作地址"
        name="farmingAddress"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.farmingAddress" allowClear />
      </a-form-item>
      <a-form-item
        v-if="!props.curRow.orderId"
        label="耕作时间"
        name="startTime"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-date-picker
          v-model:value="formData.startTime"
          valueFormat="YYYY-MM-DD"
          format="YYYY-MM-DD"
        />
      </a-form-item>
      <a-form-item
        v-if="!props.curRow.orderId"
        label="申请人姓名"
        name="applyUserName"
        :rules="[{ required: true, message: '请输入' }]"
      >
        <a-input v-model:value="formData.applyUserName" allowClear />
      </a-form-item>
      <a-form-item
        v-if="!props.curRow.orderId"
        label="申请人联系电话"
        name="applyUserPhone"
        :rules="phoneRule"
      >
        <a-input v-model:value="formData.applyUserPhone" allowClear />
      </a-form-item>
      <a-form-item
        label="接单人员"
        name="receiveUserId"
        v-if="props.curRow.orderId"
        :rules="[{ required: true, message: '请选择' }]"
      >
        <a-form-item-rest>
          <SltFromTable
            v-model="formData.receiveUserId"
            :component="SysUser"
            :fieldNames="{ name: 'applyName', id: 'memId' }"
            :nameValue="formData.receiveUserName"
            :params="{ isDriver: 1 }"
          />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item label="接单人员" name="receiveUserId" v-else>
        <a-form-item-rest>
          <SltFromTable
            v-model="formData.receiveUserId"
            :component="SysUser"
            :fieldNames="{ name: 'applyName', id: 'memId' }"
            :nameValue="formData.receiveUserName"
            :params="{ isDriver: 1 }"
          />
        </a-form-item-rest>
      </a-form-item>
      <a-form-item v-if="!props.curRow.orderId" label="备注" name="serviceRemark">
        <a-input v-model:value="formData.serviceRemark" allowClear />
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="display: flex; gap: 5px">
        <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading"
          >提交</a-button
        >
        <a-button type="primary" ghost @click="show = false">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>
